<?php
require_once '../config_site.php';
require_once 'twitteroauth.php';
require_once 'user.php';
session_start();

if (!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])) {
    // We've got everything we need
    $twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Let's request the access token
    $access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save it in a session var
    $_SESSION['access_token'] = $access_token;
// Let's get the user's info
//https://dev.twitter.com/docs/api/1/get/account/verify_credentials
    $user_info = $twitteroauth->get('account/verify_credentials');
// Print user's info

    if (isset($user_info->error)) {
        // Something's wrong, go back to square 1  
        header('Location: /');
    } else {
        $uid = $user_info->id;
        $user = new User();
        $userdata = $user->checkUser($uid, 'twitter', $user_info->screen_name);
        if(!empty($userdata)){
            session_start();
            $_SESSION['user']['id'] = $userdata['id'];
            $_SESSION['user']['oauth_id'] = $uid;
            $_SESSION['user']['oauth_provider'] = 'twitter';
            $_SESSION['user']['username'] = $user_info->screen_name;
            $_SESSION['user']['name'] = $user_info->name;
            $_SESSION['user']['avatar'] = $user_info->profile_image_url;
            $_SESSION['user']['role'] = $userdata['role'];
            $_SESSION['user']['settings'] = array('character'=>$userdata['character'],
                                                  'items'=>$userdata['items'],
                                                  'weak'=>$userdata['weak'],
                                                  'sort_by'=>$userdata['sort_by']);
            header("Location: /");
        }
    }
} else {
    // Something's missing, go back to square 1
    header('Location: login-twitter.php');
}
?>
